package uia.alumni.profile;

import java.io.PrintWriter;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnit;
import javax.servlet.http.HttpServletRequest;

import uia.alumni.data.Role;
import uia.alumni.data.User;
import uia.alumni.web.Page;
import static uia.alumni.form.FieldType.*;
import static uia.alumni.profile.Constants.*;
import static uia.alumni.web.Constants.*;

/**
 * Create Password form for user.
 * Simon Zimmermann.
 */
public class EditPassword extends Page {

    public static final String SERVLET_NAME = "profile.editpassword";
    @PersistenceUnit(name = PERSISTENCE_UNIT)
    private EntityManagerFactory emf;

    public EditPassword() {
        super(Role.member);
    }

    /**
     * Write a form for changing the password.
     * @param out
     * @param request
     */
    public void writeBody(PrintWriter out, HttpServletRequest request) {
        try {
            EntityManager em = emf.createEntityManager();
            User user = getUser(em, request);

            if (user != null) {
                String suid = Long.toString(user.getUid());
                out.println("<h1>Edit Password</h1>");

                // If form has been submitted and had errors. This will show them.
                writeFormErrors(out, request);
                out.println("<ul>");
                out.println(tagForm(SavePassword.SERVLET_NAME));
                // --------------- INPUT: ( name       | type     | label)
                if(!isAdmin(em, request)) // We only need to set the old pw if normal User.
                    out.println(tagLi(tagField(OLDPASSWORD, PW, "Old Password:")));
                out.println(tagLi(tagField(PASSWORD, PW, "New Password:")));
                out.println(tagLi(tagField(PASSWORD, PW, "Repeat New Password:")));
                out.println(tagLi(tagField(SUBMIT.toString(), SUBMIT)));
                out.println("</form>");
                out.println("<ul>");
            }
        } catch (Exception e) {
        } finally {
        }
    }
    public final static long serialVersionUID = 1;
}
